package procsim;

import java.util.*;

public class MSignalArray implements Sig, Updateable {
    private int num;
    private MSignal[] signals;
    private String name;
    private ArrayList<Updateable> elements;
    public MSignalArray(MSignal[] sig){
        num=sig.length;
        signals=sig;
    }
    public MSignalArray(MSignal[] sig, String nam){
        this(sig);
        name=nam;
    }
    public MSignalArray(MSignal sig){
        signals=new MSignal[num=1];
        signals[0]=sig;
    }
    public MSignalArray(MSignal sig, String nam){
        this(sig);
        name=nam;
    }
    @Override
    public int get(){
        return 0; // nema smisla
    }
    public MSignal[] getSignals(){
        return signals;
    }
    public MSignal getSignal(int index){
        if(index>=0 && index<num)
            return signals[index];
        else {
            System.err.println("Pristup nepostojecem signalu neuspesan!");
            return null;
        }
    }
    @Override
    public MSignalArray not(){
        for(int i=0; i<num; i++)
            signals[i].not();
        if(elements!=null) applySignalToElements();
        return this;
    }
    @Override
    public String toString(){
        String s="[";
        for(int i=num-1; i>=0; i--)
            s+=signals[i]+(i==0 ? "" : ", ");
        return s+"]";
    }
    @Override
    public String getName(){
        return name;
    }
    @Override
    public MSignalArray setName(String str){
        name = str;
        return this;
    }
    @Override
    public boolean isNull(){
        for(int i=0; i<num; i++)
            if(!signals[i].isNull())
                return false;
        return true;
    }
    public int getNumOfSignals(){
        return num;
    }
    public MSignalArray set(MSignalArray sig){
        for(int i=0; i<num; i++)
            signals[i].set(new MSignal(sig.getSignal(i).getNumOfBits(), sig.getSignal(i).get()));
        if(elements!=null) applySignalToElements();
        return this;
    }
    @Override
    public void updateSignal(Sig sig) {
        for(int i=0; i<signals.length; i++){
            signals[i].set(sig.get(), false);
        }
    }
    @Override
    public MSignalArray addElement(Updateable elem) {
        if(elements==null)
            elements = new ArrayList<Updateable>();
        if(!elements.contains(elem))
            elements.add(elem);
        return this;
    }
    private void applySignalToElements(){
        if(elements==null) return;
        Iterator iter = elements.iterator();
        while(iter.hasNext())
            ((Updateable)iter.next()).updateSignal(this);
    }
}
